package com.yunmang.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.yunmang.DaoUtils.CommonDaoUtils;
import com.yunmang.R;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.DatabaseEntity.EndStationBean;
import com.yunmang.entity.LoginBean;
import com.yunmang.entity.PackageBean;
import com.yunmang.entity.UpdateVersionBean;
import com.yunmang.http.DownLoadApi;
import com.yunmang.http.DownloadProgressHandler;
import com.yunmang.http.HttpUtils;
import com.yunmang.http.ProgressHelper;
import com.yunmang.service.UpdateService;
import com.yunmang.utils.CheckUtils;
import com.yunmang.utils.SharedPreferencesUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;

/**
 * 作者 : bean on 2017/4/6/0006.
 * 注释 :
 */
public class LoginActivity extends BaseActivity implements OnItemClickListener {

    @InjectView(R.id.remeber)
    CheckBox remeber;
    private EditText userName;
    private EditText password;
    private View vPhoneLine, vPwdLine;
    private Button button;
    private String userNameString;
    private String passwordwordString;
    private Subscriber subscriber;
    private String isKeep = "0";// 1 保存账号密码 0不
    private long exitTime = 0;
    List<PackageBean.ModelBean.BalanceMethodBean> list=new ArrayList<>();
    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        CommonDaoUtils.init(context);
        ButterKnife.inject(this);
        userName = (EditText) findViewById(R.id.user_name);
        password = (EditText) findViewById(R.id.password);
        vPhoneLine = findViewById(R.id.line_phone);
        vPwdLine = findViewById(R.id.pwd_line);
        button = (Button) findViewById(R.id.login);
        if (null != SharedPreferencesUtils.getParameter(this,"keep")) {
            isKeep = SharedPreferencesUtils.getParameter(this,"keep");
            if ("0".equals(isKeep)) {
                remeber.setChecked(false);
            } else if ("1".equals(isKeep)) {
                remeber.setChecked(true);
                userName.setText(SharedPreferencesUtils.getParameter(this, "userName"));
                password.setText(SharedPreferencesUtils.getParameter(this, "password"));
                button.setEnabled(true);
            }
        }
    }

    @Override
    public void initData() {
        userName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                                              @Override
                                              public void onFocusChange(View view, boolean b) {
                                                  if (b) {
                                                      vPhoneLine.setBackgroundColor(getResources().getColor(R.color.light_blue));
                                                  } else {
                                                      vPhoneLine.setBackgroundColor(getResources().getColor(R.color.light_gray));
                                                  }
                                              }
                                          }
        );
        password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    vPwdLine.setBackgroundColor(getResources().getColor(R.color.light_blue));
                } else {
                    vPwdLine.setBackgroundColor(getResources().getColor(R.color.light_gray));
                }
            }
        });
        userName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(userName.getText().toString()) && !TextUtils.isEmpty(password.getText().toString())) {
                    button.setEnabled(true);
                } else {
                    button.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(userName.getText().toString()) && !TextUtils.isEmpty(password.getText().toString())) {
                    button.setEnabled(true);
                } else {
                    button.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        remeber.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    isKeep = "1";
                } else {
                    isKeep = "0";
                }
            }
        });
        checkversion();

    }

    @Override
    public void dealCommon() {
        super.dealCommon();
        button.setOnClickListener(this);
    }

    @Override
    public void onInnerClick(View v) {
        super.onInnerClick(v);
        switch (v.getId()) {
            case R.id.login:
                //跳转至首页
//                Intent intent = new Intent(context,HomePageActivity.class);
//                startActivity(intent);
                checkLoginResult();
                break;
        }
    }

    private void checkLoginResult() {
        userNameString = userName.getText().toString().trim();
        passwordwordString = password.getText().toString().trim();
        if (TextUtils.isEmpty(userNameString) || TextUtils.isEmpty(passwordwordString)) {
            showToast("用户名和密码不能为空");
        } else {
            //Todo 调接口校验信息
            login(userNameString, passwordwordString);
        }
    }

    private void login(String userName, String password) {
        showWaitingDialog("正在登录中……");
        Map<String, String> params = new HashMap<>();
        params.put("userName", userName);
        params.put("password", password);
        subscriber = new Subscriber<LoginBean>() {
            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                Toast.makeText(context, "onError" + e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(LoginBean loginBean) {
                hideWaitingDialog();
                if (200 == loginBean.getCode()) {
                    //获取到数据需要存储起来
                    saveCommonData(loginBean);

                    Intent intent = new Intent(context, HomePageActivity.class);
                    startActivity(intent);
                } else if (300 == loginBean.getCode()) {
                    showToast("密码不正确");
                } else {
                    showToast("数据错误");
                }

            }
        };
        HttpUtils.getInstance().login(subscriber, params);
    }

    // 得到list
    @SuppressWarnings("unchecked")
    private List<PackageBean.ModelBean.BalanceMethodBean> getList() {
        SharedPreferences sharedPreferences = getSharedPreferences(AppConstant.balance_file, Context.MODE_PRIVATE);
        String liststr = sharedPreferences.getString("orderlist", "");
        try {
            list = SharedPreferencesUtils.String2SceneList(liststr);
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 根据登录返回的数据存储
     *
     * @param loginBean
     */
    private void saveCommonData(LoginBean loginBean) {
        AppConstant.balanceMethodList=getList();
        AppConstant.username=userNameString;
        //保存数据到文件中
        SharedPreferencesUtils.saveParameter(this, "userName",userNameString);
        SharedPreferencesUtils.saveParameter(this, "password", passwordwordString);
        SharedPreferencesUtils.saveParameter(this, "keep", isKeep);
        //删除到站表
        Boolean isdelete=CommonDaoUtils.getEndManagerInstance().deleteAll(EndStationBean.class);
        AppConstant.endOrgList = loginBean.getModel().getEndOrgList();
        AppConstant.orgInfo = loginBean.getModel().getBizOrg();
        AppConstant.userid = loginBean.getModel().getId() + "";
        AppConstant.type=loginBean.getModel().getBizOrg().getType()+"";
        List<LoginBean.ModelBean.EndOrgListBean> endList = loginBean.getModel().getEndOrgList();
        List<EndStationBean> endStationList = new ArrayList<>();
        for (LoginBean.ModelBean.EndOrgListBean bean : endList) {
            EndStationBean end = new EndStationBean();
            end.setId(bean.getId() + "");
            end.setName(bean.getName());
            end.setShortName(bean.getShortName());
            end.setSpelling(bean.getSpelling());
            end.setType(bean.getType() + "");
            endStationList.add(end);
        }
        CommonDaoUtils.getEndManagerInstance().insertMultObject(endStationList);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }



    private void checkversion() {
        subscriber=new Subscriber<UpdateVersionBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(UpdateVersionBean updateVersionBean) {
                if(updateVersionBean.getCode()==200){
                    String version = updateVersionBean.getModel().getVersion();
                    String apkUrl = updateVersionBean.getModel().getApkUrl();
                    String baseUrl=updateVersionBean.getModel().getBaseUrl();
                    if (!CheckUtils.getVersion(context).equalsIgnoreCase(version)){
                        showDialog(version,true,apkUrl,baseUrl);
                    }else{
                    }
                }else{
                    showToast("获取版本信息失败");
                }
            }
        };
        HttpUtils.getInstance().checkVersion(subscriber);
    }

    private void showDialog(String v, boolean isUpgrade, final String apkUrl, final String baseurl) {

        new AlertView("发现新版本", "博特利华新版:" + v + " , 是否下载", isUpgrade ? null : "取消", new String[]{"确定"},
                null,this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                switch (position) {
                    case 0:
                        retrofitDownload(baseurl,apkUrl);
                        break;

                }
            }
        }).show();
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast("再点一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private void retrofitDownload(String baseurl, String apkUrl){
        //监听下载进度
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setProgressNumberFormat("%1d KB/%2d KB");
        dialog.setTitle("下载");
        dialog.setMessage("正在下载，请稍后...");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.show();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseurl)
                .callbackExecutor(new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
                        new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false)));
        OkHttpClient.Builder builder = ProgressHelper.addProgress(null);
        DownLoadApi retrofit = retrofitBuilder
                .client(builder.build())
                .build().create(DownLoadApi.class);

        ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
            @Override
            protected void onProgress(long bytesRead, long contentLength, boolean done) {
                Log.e("是否在主线程中运行", String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
                Log.e("onProgress",String.format("%d%% done\n",(100 * bytesRead) / contentLength));
                Log.e("done","--->" + String.valueOf(done));
                dialog.setMax((int) (contentLength/1024));
                dialog.setProgress((int) (bytesRead/1024));

                if(done){
                    dialog.dismiss();
                }
            }
        });

        Call<ResponseBody> call = retrofit.retrofitDownload(apkUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.e("Tag", Thread.currentThread().getName());
                try {
                    InputStream is = response.body().byteStream();
//                    File file = new File(Environment.getExternalStorageDirectory(), "better.apk");
                    File file = new File(context.getExternalCacheDir(), "better.apk");
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        fos.flush();
                    }
                    fos.close();
                    bis.close();
                    is.close();
                    installApk(file);
                } catch (Exception e) {
                    showToast("出现了异常！");
                    showAlertDialog("提示","更新失败，不能更新");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    /**
     * 弹出对话框
     * @param string
     * */
    private void showAlertDialog(String hint,String string) {
        new AlertView(hint,string, null,new String[]{"确定"}, null,this,AlertView.Style.Alert,this).show();
    }

    private void installApk(File file) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        intent.setDataAndType(Uri.fromFile(file), type);
        startActivity(intent);
        finish();
    }

    @Override
    public void onItemClick(Object o, int position) {

    }
}
